import React, {Component} from 'react';
import {
    StyleSheet, 
    View,
    Text,
    FlatList,
    Image,
    TouchableOpacity,
    DeviceEventEmitter,
} from 'react-native';
import CheckBox from 'react-native-check-box'

import { RRCLoading, RRCToast, RRCAlert } from 'react-native-overlayer';

import { getPixel, getScreenWidth, getScreenHeight } from '../common/common';
import DashLine from './DashLine';

import HttpUtil from '../util/HttpUtil';
import {NavigationEvents} from 'react-navigation';

// const data = [
//     { id:1, name:'IBMX3128服务器', rfid:'AC8231749888', state:'迁入', owner: '刘云天', dept:'信息部', sn:'483758932', poistion:'A09机房', unit:'22', biz:'ERP', rack:'A30-1', cat:'服务器' }, 
//     // { id:2, name:'IBMX3128服务器', rfid:'AC8231749888', state:'在用', owner: '刘云天', dept:'信息部', sn:'483758932', poistion:'A09机房', unit:'22', biz:'ERP', rack:'A30-1', cat:'服务器' },   
//     // { id:3, name:'IBMX3128服务器', rfid:'AC8231749888', state:'在用', owner: '刘云天', dept:'信息部', sn:'483758932', poistion:'A09机房', unit:'22', biz:'ERP', rack:'A30-1', cat:'服务器' },   
//     // { id:4, name:'IBMX3128服务器', rfid:'AC8231749888', state:'在用', owner: '刘云天', dept:'信息部', sn:'483758932', poistion:'A09机房', unit:'22', biz:'ERP', rack:'A30-1', cat:'服务器' },   
//     // { id:5, name:'IBMX3128服务器', rfid:'AC8231749888', state:'在用', owner: '刘云天', dept:'信息部', sn:'483758932', poistion:'A09机房', unit:'22', biz:'ERP', rack:'A30-1', cat:'服务器' },   
//     // { id:6, name:'IBMX3128服务器', rfid:'AC8231749888', state:'在用', owner: '刘云天', dept:'信息部', sn:'483758932', poistion:'A09机房', unit:'22', biz:'ERP', rack:'A30-1', cat:'服务器' },   
//     // { id:7, name:'IBMX3128服务器', rfid:'AC8231749888', state:'在用', owner: '刘云天', dept:'信息部', sn:'483758932', poistion:'A09机房', unit:'22', biz:'ERP', rack:'A30-1', cat:'服务器' },   
//     // { id:8, name:'IBMX3128服务器', rfid:'AC8231749888', state:'在用', owner: '刘云天', dept:'信息部', sn:'483758932', poistion:'A09机房', unit:'22', biz:'ERP', rack:'A30-1', cat:'服务器' },   
//     // { id:9, name:'IBMX3128服务器', rfid:'AC8231749888', state:'在用', owner: '刘云天', dept:'信息部', sn:'483758932', poistion:'A09机房', unit:'22', biz:'ERP', rack:'A30-1', cat:'服务器' },   
//     // { id:10, name:'IBMX3128服务器', rfid:'AC8231749888', state:'在用', owner: '刘云天', dept:'信息部', sn:'483758932', poistion:'A09机房', unit:'22', biz:'ERP', rack:'A30-1', cat:'服务器' },   
// ];

let pageNo = 1; //当前第几页
let totalPage = 0; //总的页数
let searchNum = '';
let keyWord = '';


const buttons = [
    { text: '取消', style: { color: '#999', fontWeight: 'bold' } },
    { text: '确定', style: { color: '#999', fontWeight: 'bold' } }
];
let alertFlag = '';

export default class AssetMoveCard extends Component {

    constructor(props){
        super(props);

        this.state={
          selectedAsset: [],
          isChecked:false,
          count: 0,
          pageIds: [],
          data: [],
          showFoot: 0,
        }

        RRCAlert.setAlertOptions({
            alertBackgroundColor: 'rgba(0,0,0,0,0)', // alert蒙层的背景色
            titleViewStyle: {},
            titleTextStyle: {},
            contentTextStyle: {}
        })
    }

    componentDidMount() {

        this.listener = DeviceEventEmitter.addListener('moveScan', (code) => {
            searchNum = code;
            keyWord = '';
            pageNo = 1;
            this.fetchData( pageNo, searchNum, keyWord );
        })
        this.listener1 = DeviceEventEmitter.addListener('moveSubmit', (text) => {
            searchNum = '';
            keyWord = text;
            pageNo = 1;
            this.fetchData( pageNo, searchNum, keyWord );
        })

        this.listener2 = DeviceEventEmitter.addListener('moveChange', () => {
            searchNum = '';
            keyWord = '';
            pageNo = 1;
            this.fetchData( pageNo, searchNum, keyWord );
        })

        searchNum = '';
        keyWord = '';
        pageNo = 1;
        this.fetchData( pageNo, searchNum, keyWord );
    }

    componentWillUnmount() {

        if(alertFlag){
            RRCAlert.hide(alertFlag);
        }
        //移除监听
        if (this.listener) {
          this.listener.remove();
        }
        if (this.listener1) {
            this.listener.remove();
        }
        if (this.listener2) {
            this.listener2.remove();
        }
        this.setState = (state,callback)=>{
            return;
        };
    }

    fetchData = ( pageNo ) => {  
        RRCLoading.setLoadingOptions({
            text: '加载中',
            loadingBackgroundColor: 'rgba(0,0,0,0.0)',
            loadingViewStyle: {backgroundColor: 'rgba(0,0,0,0.8)'},
            loadingTextStyle: {}
        })     
        RRCLoading.show();
        let params = {
            listType: 3,
            keyWord: keyWord,
            searchNum: searchNum,
            pageNum: pageNo,
            pageSize: 10,
        }

        HttpUtil.post('listData', params)
            .then(result => { 
                if(result.httpCode == 200){ 
                   
                    let foot = 0;      
                    totalPage = result.data.assetList.pages; //获取总页数
                    //console.log('pageNo:' + pageNo + ' totalPage:' + totalPage);
                    if(pageNo>=totalPage){
                        
                        foot = 1;//listView底部显示没有更多数据了
                    }
                    let pageIds = [];
                    result.data.assetList.records.forEach(function(value) {
                        pageIds.push(value.id_);
                    });
                    if(pageNo == 1){
                        this.setState({
                            data:[],
                        });
                    }
                    this.setState({
                        isChecked: false,
                        data: [...this.state.data,...result.data.assetList.records],
                        count: result.data.moveCount,
                        pageIds: pageIds,
                        showFoot:foot,
                    });
                    RRCLoading.hide();
                }else{
                    RRCLoading.hide();
                    RRCToast.show('系统异常', 1, 3000);
                }
            })
            .catch(error => {
                RRCLoading.hide();
                RRCToast.show('系统异常', 1, 3000);
            })
    }

    _onEndReached(){
        //console.log('pageNo:' + pageNo + ' totalPage:' + totalPage);
        //如果是正在加载中或没有更多数据了，则返回
        if(this.state.showFoot != 0 ){
             return ;
        }
        //如果当前页大于或等于总页数，那就是到最后一页了，返回
        if((pageNo!=1) && (pageNo>=totalPage)){
            return;
        } else {
            pageNo++;
        }
        //底部显示正在加载更多数据
        this.setState({ showFoot:2 });
        //获取数据
        this.fetchData( pageNo, searchNum, keyWord );
    }

    _renderFooter(){
        if (this.state.showFoot === 1) {
            return (
                <View style={{ height:getPixel(30), alignItems:'center', marginTop:getPixel(10), justifyContent:'flex-start' }}>
                    <Text style={{ color:'#999999', fontSize:getPixel(14), marginBottom:getPixel(5) }}>
                        没有更多数据了
                    </Text>
                </View>
            );
        } else if(this.state.showFoot === 2) {
            return (
                <View style={{ height:getPixel(30), alignItems:'center', marginTop:getPixel(10), justifyContent:'flex-start' }}>
                    <Text style={{ color:'#999999', fontSize:getPixel(14), marginBottom:getPixel(5) }}>正在加载更多数据...</Text>
                </View>
            );
        } else if(this.state.showFoot === 0){
            return (
                <View style={styles.footer}>
                    <Text></Text>
                </View>
            );
        }
    }


    renderItem(item){
        return (
            <View key={item.id_} style={{ flexDirection: 'row', paddingLeft: getPixel(15), marginTop: getPixel(10), paddingRight: getPixel(15), paddingBottom: getPixel(20), paddingTop: getPixel(10), backgroundColor:'#FFF' }}>
                <View style={{ width: getPixel(30), alignItems: 'flex-start' }}>
                    <CheckBox
                        style={{ flex: 1, width: getPixel(20), height: getPixel(40),  justifyContent: 'flex-start', paddingTop: getPixel(10) }}
                        unCheckedImage={ <Image source={ require('../images/unchecked.png')} style={{  resizeMode: 'contain', width: getPixel(20), height: getPixel(20), }} /> }
                        checkedImage={ <Image source={ require('../images/checked.png')} style={{  resizeMode: 'contain', width: getPixel(20), height: getPixel(20), }} /> }
                        onClick={()=>{
                            let selected = Array.from(this.state.selectedAsset);
                            if(selected.includes(item.id_)){
                                selected.splice(selected.findIndex(i => i === item.id_), 1)
                            }else{
                                selected.push(item.id_);
                            }
                            this.setState({
                                selectedAsset: selected,
                            })
                            if(selected.length !== this.state.pageIds.length){
                                this.setState({
                                    isChecked: false,
                                })
                            }
                        }}
                        isChecked={ this.state.selectedAsset.includes(item.id_) }
                        rightTextStyle={{ color: '#999' }}
                    />
                </View>
                <View style={{ width: getScreenWidth() - getPixel(30) }}>    
                    <View style={styles.cardTitle}>
                        <View style={styles.assetTag}>
                            <Text style={{ fontSize: getPixel(16), color:'#333' }}>
                                {item.assetName}
                            </Text>
                            <Text style={{ fontSize: getPixel(14), color:'#999' }}>
                                RFID: {item.rfidNo}
                            </Text>
                        </View>
                        <View style={styles.assetState}>
                            <Text style={styles.assetStateText}>
                                {item.statusName}
                            </Text>
                        </View>  
                    </View>
                    <View style={styles.cardInfo}>
                        <View style={styles.assetInfo}>
                            <View style={styles.assetInfoBasic}>
                                <View style={styles.assetInfoBasicOwner}>
                                    <Text style={[{ fontSize: getPixel(16), color:'#333' }, item.manageUser ? {marginRight : getPixel(5)} : null]}>
                                        {item.manageUser}
                                    </Text>
                                    <Text style={ styles.assetInfoBasicDept }>
                                        {item.manageBranchName}
                                    </Text>
                                </View>
                                <Text style={{ fontSize: getPixel(14), color:'#999' }}>
                                    SN: {item.serialNo}
                                </Text>
                            </View>
                            <DashLine backgroundColor='#EEE' len={35} width={210} marginTop={getPixel(10)}  marginBottom={getPixel(10)} />
                            <View style={styles.assetInfoOther}>
                                <View style={styles.assetInfoOtherText}>
                                    <Text numberOfLines={1} style={{ fontSize: getPixel(14), color:'#999',width: getPixel(115) }}>
                                        位置：{item.roomName}
                                    </Text>
                                    <Text numberOfLines={1} style={{ fontSize: getPixel(14), color:'#999',width: getPixel(100) }}>
                                        U位：{item.startU} - {item.endU}
                                    </Text>
                                </View>
                                <View style={styles.assetInfoOtherText}>
                                    <Text numberOfLines={1} style={{ fontSize: getPixel(14), color:'#999',width: getPixel(115) }}>
                                        业务：{item.modelName}
                                    </Text>
                                    <Text numberOfLines={1} style={{ fontSize: getPixel(14), color:'#999',width: getPixel(100) }}>
                                        机柜：{item.rackName}
                                    </Text>
                                </View>
                                <View style={styles.assetInfoOtherText}>
                                    <Text numberOfLines={1} style={{ fontSize: getPixel(14), color:'#999',width: getPixel(115) }}>
                                        类型：{item.typeName}
                                    </Text>
                                </View>
                            </View>
                        </View>
                        <View style={styles.assetImg}>
                            <Image source={ item.imgPath? { uri: item.imgPath } : require('../images/noimg.png') } style={ styles.img } />
                        </View>
                    </View>
                </View>
            </View>
        )
    }

    add = () => {
        this.props.navigation.navigate('AddMove', {
            tab: 2,
            callBack: () => {
                this.setState({
                    data:[],
                });
                pageNo = 1;
                searchNum = '';
                keyWord = '';
                this.fetchData(pageNo, searchNum, keyWord );
            }        
        });
    }

   

    submit = () => {

        if(this.state.selectedAsset.length <=0){
            RRCToast.show('请选择要迁移资产', 2, 2000);
            return;
        }
        alertFlag =  RRCAlert.alert('确定迁移', '确定您要迁移选择的资产？', buttons, (index) => {
            if( index===1 ){
                RRCLoading.setLoadingOptions({
                    text: '请稍候',
                    loadingBackgroundColor: 'rgba(0,0,0,0.0)',
                    loadingViewStyle: {backgroundColor: 'rgba(0,0,0,0.8)'},
                    loadingTextStyle: {}
                })
                RRCLoading.show();
                //console.log(this.state.selectedAsset);
                HttpUtil.post('confirmMove', this.state.selectedAsset)
                .then(result => {         
                    //console.log(result);
                    if(result.httpCode == 200){
                        this.setState({
                            selectedAsset: [],
                        });
                        pageNo = 1;
                        searchNum = '';
                        keyWord = '';
                        this.fetchData(pageNo, searchNum, keyWord );
                        RRCLoading.hide();
                        RRCToast.show('迁移成功', 2, 3000);
                    }else{
                        RRCLoading.hide();
                        RRCToast.show('系统异常', 1, 3000);
                    }
                })
                .catch(error => {
                    //console.log(error);
                    RRCLoading.hide();
                    RRCToast.show('系统异常', 1, 3000);
                })
            }
        });
    }

    render() {
        return (
            <View  style={styles.container}>
                <NavigationEvents onDidBlur={() => this.componentWillUnmount()}/>
                <View style={{ flexDirection: 'row', }}>
                        <Text style={{ width: getScreenWidth() - getPixel(70), height:getPixel(40), lineHeight:getPixel(40), paddingLeft:getPixel(15), color: '#999', fontSize: getPixel(15) }}>准备迁移数量: {this.state.count}</Text>
                        <CheckBox
                            style={{ flex: 1, width: getPixel(20), height: getPixel(40),  justifyContent: 'center' }}
                            unCheckedImage={ <Image source={ require('../images/unchecked.png')} style={{  resizeMode: 'contain', width: getPixel(20), height: getPixel(20), }} /> }
                            checkedImage={ <Image source={ require('../images/checked.png')} style={{  resizeMode: 'contain', width: getPixel(20), height: getPixel(20), }} /> }
                            onClick={()=>{
                                //console.log(this.state.pageIds);
                                this.setState({
                                    isChecked:!this.state.isChecked,
                                    selectedAsset: !this.state.isChecked ? this.state.pageIds: [],
                                })
                                
                            }}
                            isChecked={this.state.isChecked}
                            rightText={ '全选' }
                            rightTextStyle={{ color: '#999' }}
                        />
                </View>
                <FlatList
                    style={{ backgroundColor: '#F5F5F5' }}
                    data={this.state.data}
                    renderItem={({item}) => this.renderItem(item)}
                    keyExtractor={(item, index) => index.toString()}
                    onEndReached={this._onEndReached.bind(this)}
                    onEndReachedThreshold={1}
                    ListFooterComponent={this._renderFooter.bind(this)}
                >
                </FlatList>
                <View style={styles.buttonGroup}>
                    <TouchableOpacity onPress={this.add}>
                        <View style={styles.buttonSearch}>
                            <Text style={{ color: '#FFFFFF', textAlign: 'center', fontSize: getPixel(16), lineHeight: getPixel(40) }}>新增</Text>
                        </View>
                    </TouchableOpacity> 
                    <TouchableOpacity onPress={this.submit}>
                        <View style={styles.buttonSave}>
                            <Text style={{ color: '#FFFFFF', textAlign: 'center', fontSize: getPixel(16), lineHeight: getPixel(40) }}>确认</Text>
                        </View>
                    </TouchableOpacity>
                </View>
            </View>
            
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },

    cardTitle: {
        flexDirection: 'row',
        borderBottomColor: '#EEEEEE',
        borderBottomWidth: getPixel(1),
        width: getPixel(315)
    },
    cardInfo: {
        flexDirection: 'row',
        marginTop: getPixel(10),
    },
    assetTag: {
        width: getScreenWidth() - getPixel(140),
        height: getPixel(60),
        justifyContent: 'center',
    },
    assetInfo: {
        width: getScreenWidth() - getPixel(160),
        height: getPixel(130),
        justifyContent: 'center',
    },
    assetImg: {
        width: getPixel(100),
        height: getPixel(130),
        justifyContent: 'center',
        alignItems: 'flex-end',
    },
    assetInfoBasic: {
        justifyContent: 'center',
    },
    assetInfoOther: {
        justifyContent: 'center',
    },
    assetInfoOtherText: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    assetInfoBasicOwner: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    assetInfoBasicDept: {
        fontSize: getPixel(12), 
        color:'#FFAA2E', 
        backgroundColor:'#FFF9EF',
        borderColor: '#FFAA2E',
        borderWidth: 1,
        padding: getPixel(2),
        paddingLeft: getPixel(4),
        height: getPixel(20),
    },
    img: {
        resizeMode: 'contain', 
        width: getPixel(100), 
        height: getPixel(100),
    },
    assetState: {
        width: getPixel(80),
        height: getPixel(60),
        justifyContent: 'center',
        alignItems: 'flex-end',
    },
    assetStateText: {
        fontSize: getPixel(14), 
        color: '#FF5C7D', 
        width: getPixel(60),
        height: getPixel(30),
        borderColor: '#ff5c7d',
        borderWidth: 1,
        textAlign: 'center',
        lineHeight: getPixel(30),
        backgroundColor: '#ffedf0',
        borderRadius: 10,
    },
    buttonGroup: {
        flexDirection: 'row',
        paddingLeft: getPixel(20),
        paddingRight: getPixel(20),
        height: getPixel(60), 
        backgroundColor: '#FFF',
        width: getScreenWidth(),
        alignItems: 'center',
        elevation: 4,
        shadowOffset: { width: 0, height: 5 },
        shadowOpacity: 0.5,
        shadowRadius: 10,
        shadowColor: '#DDD',
        backgroundColor: '#FFF',
        position:'absolute',
        bottom: 0,
    },
    buttonSearch: {
        backgroundColor: '#6484FA', 
        height: getPixel(40), 
        borderTopLeftRadius: getPixel(10),
        borderBottomLeftRadius: getPixel(10),
        width: (getScreenWidth() - 30) / 2,
    },
    buttonSave: {
        backgroundColor: '#4a69dd', 
        height: getPixel(40), 
        borderTopRightRadius: getPixel(10),
        borderBottomRightRadius: getPixel(10),
        width: (getScreenWidth() - 30) / 2,
    },
    footer:{
        flexDirection:'row',
        height: getPixel(24),
        justifyContent:'center',
        alignItems:'center',
        marginBottom:getPixel(10),
    },
});